<template>
  <div
    class="baseTablePageComponent pagination_style"
    :class="{
      total_table_cpn: haveTotalTable,
      index_base_search: $attrs.grid
    }">
    <!-- 搜索表单 start -->
    <div
      class="baseSearch-container margin-bottom10"
      v-if="configJsonArr.length">
      <base-search
        ref="baseForm"
        :footerItem="customSearchFooter"
        :configJsonArr="configJsonArr"
        @confirm="handleSearch"
        @reset="handleReset"
        @callback="handleCallback"
        v-bind="$attrs">
        <!-- 按钮插槽 -->
        <template #footer v-if="customSearchFooter === true">
          <!-- 左边按钮 -->
          <div class="footer_item align_center between flex">
            <div class="left">
              <slot name="footerLeft"></slot>
            </div>
            <!-- 筛选按钮插槽 右边按钮-->
            <div class="right">
              <slot name="footerRight">
                <a-button
                  class="margin-right16"
                  type="primary"
                  html-type="submit"
                  >查询</a-button
                >
                <a-button @click="reset">重置</a-button>
              </slot>
            </div>
          </div>
        </template>
      </base-search>
    </div>

    <!-- table 头部插槽 -->
    <div class="table-top-template">
      <slot name="TableTop"></slot>
    </div>

    <!-- table-container start -->
    <div class="table-container">
      <!-- table 支持自定义内容 -->
      <slot name="table">
        <!-- table 插槽默认内容 -->
        <a-table
          :class="[tableData.length ? 'base_table' : '']"
          ref="table"
          :row-selection="
            haveRowSelection
              ? {
                  selectedRowKeys: selectedRowKeys,
                  onChange: rowSelectionChange
                }
              : null
          "
          :pagination="false"
          :data-source="tableData"
          :columns="columns"
          @change="handleTableChange"
          v-bind="$attrs.AntDTableApi">
          <!-- 表格内容插槽 
          使用一：<template slot="project" slot-scope="{ text, record }">
                  <span>{{ text }}</span>
                </template>
          使用二：<template v-slot:project="{ text, record }">
                    <span>{{ text }}</span>
                  </template>
      -->
          <template
            v-for="column in columns"
            :slot="column.scopedSlots ? column.scopedSlots.customRender : ''"
            slot-scope="text, record, index">
            <slot
              :name="column.scopedSlots ? column.scopedSlots.customRender : ''"
              v-bind="{ text, record, index }">
              <span v-if="column.isMoney" :key="column.dataIndex || column.key">
                {{ text | formatAmount }}
              </span>
              <span v-else>{{ text }}</span>
            </slot>
          </template>

          <!-- 表头插槽 -->
          <template
            v-for="column in columns"
            :slot="column.slots ? column.slots.title : ''">
            <slot
              v-for="column in columns"
              :name="column.slots ? column.slots.title : ''"></slot>
          </template>
        </a-table>

        <!-- 合计表格 -->
        <a-table
          class="total_table"
          v-if="haveTotalTable"
          :scroll="tableData.length ? { x: true } : { x: false }"
          ref="totalTable"
          rowKey="id"
          :pagination="false"
          :columns="formatColumns"
          :data-source="formatTotalTableData">
          <!-- 需要修改为合计的行  total_roject为
            使用： <template v-slot:total_roject="{ text, record }">
                    <span>{{ text }}</span>
                  </template>
          -->
          <template
            v-for="column in formatColumns"
            :slot="column.scopedSlots ? column.scopedSlots.customRender : ''"
            slot-scope="text, record, index">
            <span v-if="column.isMoney" :key="column.dataIndex || column.key">
              {{ text | formatAmount }}
            </span>
            <slot
              v-else
              :name="column.scopedSlots ? column.scopedSlots.customRender : ''"
              v-bind="{ text, record, index }">
              <span :key="column.dataIndex || column.key">{{ text }}</span>
            </slot>
          </template>
        </a-table>
      </slot>
    </div>
    <!-- table-container end -->

    <!-- 分页 -->
    <div class="pagination-container margin-top20" v-if="pagination">
      <a-pagination
        show-size-changer
        show-quick-jumper
        :current="pagination.current"
        :total="pagination.total"
        :defaultPageSize="pagination.pageSize"
        :show-total="() => formatterShowTotal"
        @change="currentChange"
        @showSizeChange="showSizeChange" />
    </div>
  </div>
</template>

<script>
import BaseSearch from '@/components/BaseSearch'

export default {
  name: 'BaseTablePageComponent',
  components: {
    BaseSearch
  },
  props: {
    /* 表格数据 start  */
    // columns除了ant-design vue 的配置，需要再配置一个totalTableKey
    columns: {
      type: Array,
      default: () => []
    },
    // 表格展示数据
    tableData: {
      type: Array,
      default: () => []
    },
    // 是否开启可选项
    haveRowSelection: {
      type: Boolean,
      default: false
    },
    // 是否开启总数表格
    haveTotalTable: {
      type: Boolean,
      default: false
    },
    // 表格合计数据
    totalTableData: {
      type: Array,
      default: () => []
    },
    selectedRowKeys: {
      type: Array,
      default: () => []
    },
    /* 表格数据 end  */

    /* 页码 start */
    pagination: {
      type: Boolean | Object,
      default: false
    },
    /* 页码 end */

    /* 搜索 start */
    customSearchFooter: {
      type: Boolean,
      default: true
    },
    configJsonArr: {
      type: Array,
      default: () => []
    }
    /* 搜索 end */
  },
  data() {
    return {
      baseForm: null,
      tableDom: null,
      totalTableDom: null
    }
  },
  computed: {
    // 调整过的合计columns配置
    formatColumns() {
      let result = []
      if (this.haveTotalTable) {
        result = this.columns.map((item) => {
          if (item.totalTableKey) {
            return {
              ...item,
              dataIndex: item.totalTableKey || item.key,
              // 将插槽改成合计对应的字段
              scopedSlots: { customRender: item.totalTableKey }
            }
          } else {
            return {
              ...item
            }
          }
        })

        if (this.haveRowSelection) {
          let obj = {
            title: '选择框占位',
            dataIndex: 'placeholder',
            fixed: 'left',
            width: '60px'
          }
          result = [obj, ...result]
        }
      } else {
        result = [...this.columns]
      }

      return result
    },
    // 这个表格数据只有一条数据 把id写死
    formatTotalTableData() {
      let arr = this.totalTableData
      if (this.totalTableData.length) {
        ;[{ ...this.totalTableData[0], id: 1 }]
      }
      return arr
    },
    formatterShowTotal() {
      let { total, current, pageSize } = this.pagination

      let totalPage = total / pageSize
      if (totalPage.toString().split('.').length > 1) {
        totalPage = ~~totalPage + 1
      }
      return `共 ${total} 条记录 第${current}/${totalPage}页`
    }
  },
  watch: {
    tableData(newVal) {
      this.$nextTick(() => {
        if (this.haveTotalTable && newVal.length) {
          this.footerScroll()
        }
      })
    }
  },
  filters: {
    // 金额方法
    formatAmount(amount) {
      let amountS = amount ? Number(amount).toFixed(2) : '0.00'
      return `${amountS}元`
    }
  },
  mounted() {
    this.baseForm = this.$refs.baseForm
    this.tableDom = this.$refs.table
    this.totalTableDom = this.$refs.totalTable
  },
  methods: {
    /**
     * @description: 触发搜索事件
     * @param { Object } data
     * @return {*}
     */
    handleSearch(data) {
      this.$emit('confirm', data)
    },
    handleReset() {
      this.baseForm.resetForm()
      this.$emit('reset')
    },
    /**
     * @description: 搜索表单回调事件
     * @param {*} data
     * @return {*}
     */
    handleCallback(data) {
      this.$emit('callback', data)
    },
    /**
     * @description: 搜索表单重置事件
     * @return {*}
     */
    reset() {
      this.baseForm.resetForm(true)
    },
    // 列表选择
    rowSelectionChange(selectedRowKeys, selectedRows) {
      this.$emit('selectionChange', selectedRowKeys, selectedRows)
    },
    // 表格表格排序 分页、排序、筛选变化时触发
    handleTableChange(pagination, filters, sorter) {
      this.$emit('change', pagination, filters, sorter)
    },
    currentChange(page, pageSize) {
      this.$emit('currentChange', page, pageSize)
    },
    showSizeChange(current, size) {
      this.$emit('showSizeChange', current, size)
    },
    //两表格同步滚动 方法
    footerScroll() {
      let { tableDom, totalTableDom } = this
      const tableBody = tableDom.$el.getElementsByClassName('ant-table-body')[0]
      const totalTableBody =
        totalTableDom.$el.getElementsByClassName('ant-table-body')[0]

      totalTableBody.removeEventListener('scroll', syncScroll)
      totalTableBody.addEventListener('scroll', syncScroll)

      function syncScroll() {
        tableBody.scrollLeft = totalTableBody.scrollLeft
      }
    }
  }
}
</script>

<style scoped lang="less">
.total_table_cpn {
  .base_table {
    /deep/ .ant-table-body {
      overflow-x: hidden !important;
    }
  }
  .total_table {
    /deep/ .ant-table-thead {
      display: none;
    }
    /deep/ .ant-table-placeholder {
      display: none;
    }
  }
}

// 分页器样式，需要在外面加一层，类名加在外层元素上
.pagination_style {
  width: 100%;

  /* 页码导航样式 start */
  /deep/ .ant-pagination {
    width: 100%;
    display: flex;

    .ant-pagination-total-text {
      flex: 1;
    }

    .ant-pagination-item-active a {
      color: #fff;
      background: #1890ff;
    }

    .ant-pagination-item,
    .ant-pagination-item-link,
    .ant-select-selection {
      border-radius: 2px;
    }

    .ant-pagination-options-quick-jumper input {
      border-radius: 2px;
    }
  }

  /* 页码导航样式 end */
}
</style>
